#include "GL/glew.h"
#include "LoadShader.h"
#include "utility.h"
#include "vmath.h"
#include <iostream>
#include <iomanip>

#include "polyline/Polyline2D.h"

GLuint program, vao, vbo, vao1, vbo1;
int pointCount = 0;

std::vector<Vec2> points
{
		{ -300.0f, 200.0f  },
		{ -300.0f,  -200.0f  },
		{ 0.0f,  -200.0f  },
		{ 0.0f,  200.0f  },
		{ 300.0f, 200.0f  },
		{ 300.0f,  -200.0f  },
		//{ -100.0f,  100.0f  },

};

bool init()
{
	ShaderInfo si[] = { { GL_VERTEX_SHADER, "Shader.vert" },{ GL_FRAGMENT_SHADER, "Shader.frag" },{ GL_NONE, nullptr } };
	program = LoadShade(si);

	auto thickness = 30.0f;
	auto vertices = Polyline2D::create(points, thickness,
		Polyline2D::JointStyle::BEVEL,
		Polyline2D::EndCapStyle::SQUARE);
	pointCount = vertices.size();


	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(vertices[0]), vertices.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
	glEnableVertexAttribArray(0);
	glVertexAttrib4f(1, 1.0, 1.0, 1.0, 1.0);

	glGenVertexArrays(1, &vao1);
	glBindVertexArray(vao1);
	glGenBuffers(1, &vbo1);
	glBindBuffer(GL_ARRAY_BUFFER, vbo1);
	glBufferData(GL_ARRAY_BUFFER, points.size()*sizeof(points[0]), points.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
	glEnableVertexAttribArray(0);
	glVertexAttrib4f(1, 1.0, 1.0, 1.0, 1.0);

	glClearColor(0.05f, 0.1f, 0.1f, 1.0f);
	return true;
}

void Display(double time)
{
	glClear(GL_COLOR_BUFFER_BIT);
	glUseProgram(program);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	auto width = getViewWidth();
	auto height = getViewHeight();

	Matrix4f m;
	m = Matrix4f::createOrtho(-width/2, width/2, -height/2, height/2, -100, 100);
	//m = m * Matrix4f::createScale(2.0f, 2.0f, 2.0f);
	glUniformMatrix4fv(1, 1, GL_FALSE, (float*)m);

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	glUniform4f(2, 0.0f, 1.0f, 1.0f, 0.9f);
	glBindVertexArray(vao);
	glDrawArrays(GL_TRIANGLES, 0, pointCount);

	glLineWidth(1.0f);
	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	glUniform4f(2, 0.6f, 0.4f, 0.4f, 1.0f);
	glBindVertexArray(vao);
	glDrawArrays(GL_TRIANGLES, 0, pointCount);

	glUniform4f(2, 0.2f, 0.2f, 0.2f, 0.6f);
	glPointSize(10);
	glBindVertexArray(vao1);
	glDrawArrays(GL_POINTS, 0, points.size());
}

void onClose()
{
	glDeleteVertexArrays(1, &vao);
	glDeleteBuffers(1, &vbo);
}

